'''
Author: @zhyy
Date: 2021-01-31 12:05:32
LastEditors: @zhyy
LastEditTime: 2021-02-03 17:33:23
'''

from app import db
from sqlalchemy import desc, asc


class BaseModel():
    '''
    description: 定义通用的数据库处理方法基础类
    '''
    @staticmethod
    def get_one(_cls,filters,chema):
        '''
        description: 从数据库读取一条数据 
        param: object cls_ 数据库模型实体类
        param: dict filters 数据过滤条件
        param: object chema 数据库模型序列化类
        return：dict data_schema 序列化数据库数据对象
        '''
        data=db.session.query(_cls).filter(*filters).first()
        data_schema = chema().dump(data)
        return data_schema

    @staticmethod
    def get_many(_cls,filters,chema):
        '''
        description: 从数据库读取一条数据 
        param: object cls_ 数据库模型实体类
        param: dict filters 数据过滤条件
        param: object chema 数据库模型序列化类
        return：dict 序列化数据库数据对象
        '''
        data=db.session.query(_cls).filter(*filters).all()
        data_schema = chema(many=True).dump(data)
        return  data_schema
    @staticmethod
    def get_page(_cls,filters,chema,page,per_page):
        
        '''
        description: 从数据库读取一条数据 
        param: object cls_ 数据库模型实体类
        param: dict filters 数据过滤条件
        param: object chema 数据库模型序列化类
        param: int page 数据分页当前页数
        param: int per_page 数据分页每页条数
        return：dict data 序列化数据库数据对象
        '''
        page_data = db.session.query(_cls).filter(*filters).paginate(
                page, per_page, error_out=False)
        data_schema = chema(many=True).dump(page_data.items)
        data = {
        "page": page_data.page,
        "pages": page_data.pages,  # 总页数
        "page_size":per_page,  #每页条数
        "total": page_data.total,  # 数据的总条数
        "list": data_schema
        }
        return data


    def add(self, cls_, data:dict)->int:
        """
        添加
        param : object cls_ 数据库模型实体类
        param : dict data 数据
        return : bool
        """
        records = cls_(**data)
        db.add(records)
        db.flush()
        return records.id

    def edit(self, cls_:object, data:dict, filters:set)->bool:
        '''
        description: 修改
        param object cls_ 数据库模型实体类
        param dict data 数据
        param set filters 条件
        return bool
        '''
        return db.session.query(cls_).filter(*filters).update(data, synchronize_session=False)
    
    def delete(self, cls_:object, filters:set)->int:
        '''
        description: 删除
        param object cls_ 数据库模型实体类
        param set filters 条件
        return int
        '''
        return db.session.query(cls_).filter(*filters).delete(synchronize_session=False)
    
    def getCount(self, cls_:object, filters:set, field = None)->int: 
        '''
        description: 统计数量
        param object cls_ 数据库模型实体类
        param set filters 条件
        param obj field 字段
        return int
        '''
        if field == None:
            return db.session.query(cls_).filter(*filters).count()
        else:
            return db.session.query(cls_).filter(*filters).count(field)

    @staticmethod
    def get_sigle_table_page(_cls,filters,page,per_page):
        page_data = db.session.query(_cls).filter(*filters).paginate(
                        page=page, per_page=page_data, error_out=False)
        return page_data

    @staticmethod
    def get_filed_page(keys_field,filters,page,per_page):
        '''
        description: 
        param field={"uid":User.id,"role_id":Role.id}
        return {*}
        '''
        keys_field={"id":1,"name":"uname"}
        keys=list(keys_field.keys())
        field=list(keys_field.values())
        page_data = db.session.query(*field).filter(*filters).paginate(
                        page=page, per_page=page_data, error_out=False)
        data={}
        for k,v in page_data.__dict__.items():
            if not k.startswith("query"):
                data[k]=v
        item=QueryToJson.query_table_field_to_json_list(keys,data.get("items"))
        data["items"]=item
        return data
        return page_data